package com.lpf.handler2.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()];

        //Transfers this buffer's data to the specified destination starting at the current readerIndex and increases the readerIndex by the number of the transferred bytes (= dst.length).
        //Throws:IndexOutOfBoundsException – if dst.length is greater than this.readableBytes
        msg.readBytes(bytes);

        String message = new String(bytes, CharsetUtil.UTF_8);

        System.out.println("服务端接收到的消息内容：" + message);
        System.out.println("服务端接收到的消息数量：" + (++this.count));

        ByteBuf byteBuf = Unpooled.copiedBuffer(UUID.randomUUID().toString(), CharsetUtil.UTF_8);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}